<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/7/15 上午9:20
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/7/15 上午9:20
 * @FilePath: G:/chain-link-api-front-admin/src/views/web3Tools/batchWallet\index.vue
 * @Description: 批量生成钱包地址
-->
<template>
  <div :class="{'container':true, 'move-up':showResBox}">
    <div class="formBox">
      <el-form :model="ruleForm" label-width="auto" ref="ruleRef" :rules="rules" label-position="right" center
               style="max-width: 500px; ">
        <el-form-item prop="chainId">
          <el-select v-model.trim="ruleForm.chainId" filterable :placeholder="t('assetManagement.SelectChainName')"
                     @change="changeChainId">
            <el-option v-for="(item, index) in chainList" :key="index" :label="item.chainName" :value="item.chainId"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="createNumber">
          <el-input type="number" v-model.num.trim="ruleForm.createNumber" :placeholder="t('message.WalletNumbers')"
                    @input="valueNumber"/>
        </el-form-item>
        <el-form-item style="display: flex; flex-direction: row;justify-content: space-between;align-items: center">
          <el-button type="primary" size="large" @click="onSubmit()">{{ t('global.Submit') }}</el-button>
          <el-button type="warning" size="large" @click="onExport()" v-show="walletList.length > 0">
            {{ t('button.Export') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>


    <div :class="{'resBox':true, 'scrollable-container':true, 'show':showResBox}">
      <div class="content">
        <el-card class="item" v-for="(item, key) in walletList" :key="key">
          <div class="qrcodeBox">
            <div class="id">{{ key + 1 }}</div>
            <qrcode-vue :value="item.qrUrl" :size="100" :options="qrData.qrOptions"
                        style="margin-right: 10px"></qrcode-vue>
          </div>

          <div class="right">
            <div class="top item_body">
              <el-input v-model="item.address" disabled style="max-width: 700px;width: 700px">
                <template #prepend>{{ t('tools.Address') }}</template>
                <template #append>
                  <el-button type="primary" @click="copyTextToClipboard(item.address)">{{
                      t('button.Copy')
                    }}
                  </el-button>
                </template>
              </el-input>
            </div>
            <div class="footer item_body">
              <el-input v-model="item.privateKey" disabled style="max-width: 700px; width: 700px">
                <template #prepend>{{ t('tools.PrivateKey') }}</template>
                <template #append>
                  <el-button type="primary" @click="copyTextToClipboard(item.privateKey)">{{
                      t('button.Copy')
                    }}
                  </el-button>
                </template>
              </el-input>
            </div>
            <div class="top item_body" v-if="ruleForm.chainId !== 648126">
              <el-input v-model="item.mnemonic" disabled style="max-width: 700px;width: 700px">
                <template #prepend>{{ t('tools.Mnemonic') }}</template>
                <template #append>
                  <el-button type="primary" @click="copyTextToClipboard(item.mnemonic)">{{
                      t('button.Copy')
                    }}
                  </el-button>
                </template>
              </el-input>
            </div>
            <!--              <el-divider />-->
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, unref, reactive, onMounted} from "vue";
import {ElMessage} from "element-plus";
import {getConfigList} from '@/require/api.js'
import {useClipboard} from '@vueuse/core'
import {useI18n} from "vue-i18n";
import {ethers} from "ethers";

import CryptoJS from 'crypto-js'; // 引入加密库
import QrcodeVue from 'qrcode.vue';
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';

const {t} = useI18n();

onMounted(() => {
  getChainList() // 获取链列表
})

// 链列表
const chainList = ref([])

// 表单数据
const ruleForm = reactive({
  createNumber: '',
  inpValue: '',
  chainId: undefined
})

function changeChainId(v) {
  console.log(typeof (v))
}

const walletList = ref([])
const showResBox = ref(false) // 控制resBox显隐

// 批量生成地址
function onSubmit() {
  // showDiv2.value = !showDiv2.value;
  if (!ruleForm.chainId || !ruleForm.createNumber) {
    ElMessage.error(t('message.CheckInput'))
    return
  }

  walletList.value = []
  
  if (ruleForm.chainId === 648126) {
    // 批量生成 TRX 钱包地址
    console.log('TRX')
    for (let i = 0; i < ruleForm.createNumber; i++) {
      const account = TronWeb.utils.accounts.generateAccount()
        console.log('account:', account)
        if(account){
          walletList.value.push({
            address: account.address.base58,
            privateKey: account.privateKey,
            qrUrl: account.privateKey
          });
        }
      //   console.log(TronWeb.mnemonic)
      //   console.log(account.address)


      // console.log(account)
      // console.log(TronWeb)
      // console.log(TronWeb.address.toHex(account.address.base58)) // base58 地址转为 hex
      // console.log(account.address.base58)
      // console.log(account.privateKey)
    }
    showResBox.value = true
  } else {
    // 其他链
    console.log('其他链')
    for (let i = 0; i < ruleForm.createNumber; i++) {
      const wallet = ethers.Wallet.createRandom();
      console.log(wallet)
      walletList.value.push({
        address: wallet.address,
        privateKey: wallet.privateKey,
        mnemonic: wallet.mnemonic.phrase,
        qrUrl: wallet.privateKey
      });
    }
    showResBox.value = true
  }
}

// 导出 excel
async function onExport() {
  // 准备数据
  const data = [
    ["Address", "Private Key"], // 表头
    ...walletList.value.map(wallet => [wallet.address, wallet.privateKey]) // 数据行
  ];

  // 创建工作表
  const worksheet = XLSX.utils.aoa_to_sheet(data);

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Wallets');

  // 生成Excel文件
  const excelBuffer = XLSX.write(workbook, {bookType: 'xlsx', type: 'array'});

  // 创建Blob对象
  const blob = new Blob([excelBuffer], {type: 'application/octet-stream'});

  // 保存文件
  FileSaver.saveAs(blob, 'wallets.xlsx');
}

// 获取配置信息
async function getChainList() {
  const {code, data, msg} = await getConfigList();
  if (code === 200) {
    chainList.value = data;
  }
}

const valueNumber = () => {
  ruleForm.createNumber = ruleForm.createNumber.replace(/\D/g, '')
  console.log(ruleForm.createNumber)
}

const rules = reactive({
  chainId: [{required: true, message: t("assetManagement.SelectChainName"), trigger: "blur"},],
  createNumber: [{required: true, message: t("message.WalletNumbers"), trigger: "blur"},],
});


// 当点击执行复制
const {text, copy, copied, isSupported} = useClipboard({legacy: true})
const copyTextToClipboard = async (val) => {
  console.log(val)
  try {
    await copy(unref(val));
    ElMessage.success(t('message.CopySuccess'));
  } catch (err) {
    console.error('Failed to copy text: ', err);
  }
};

const qrData = reactive({
  qrUrl: [],
  qrOptions: {
    /*
    二维码选项，可以根据需要进行配置
    L: 约 7% 或更少的错误能被纠正。
    M: 约 15% 或更少的错误能被纠正。
    Q: 约 25% 或更少的错误能被纠正。
    H: 约 30% 或更少的错误能被纠正。纠错能力越高，二维码的密集度也越高，但生成的二维码尺寸会相应增加。
    margin: 表示二维码的外边距，即二维码图案到画布边缘的距离，以模块为单位。默认为 4 个模块，可根据需要增加或减少
    scale: 表示二维码的放大倍数。默认为 4，意味着每个模块（方块）会被放大为 4 像素。增大放大倍数可以生成更大尺寸的二维码，也可以增加二维码的可读性，但会增加生成的二维码图像的尺寸
    */
    errorCorrectionLevel: 'H',
    margin: 2,
    scale: 4,
  }
})
</script>

<style scoped lang="less">
:deep(.el-select__wrapper) {
  width: 300px;
  height: 50px;
}

:deep(.el-input) {
  width: 300px;
  height: 40px;
}

:deep(.el-form-item__content) {
  display: flex;
  justify-content: space-between;
}

.container {
  //height: calc(100vh - 100px);
  //height: 100%;
  position: relative;
  transition: all 0.5s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  //background-color: #2b313c;

  .formBox {
    width: 100%;
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #2b313c;

  }

  .show {
    display: block !important;

  }

  .resBox {
    display: none;
    max-height: calc(100vh - 400px); /* 假设 formBox 需要 200px 的空间 */
    overflow-y: auto;
    width: 84vw;
    //height: 800px;
    //background-color: #f3f3f3;
    //display: flex;
    //flex-direction: column;
    //justify-content: center;
    //align-items: center;
    //padding: 20px;
    //box-sizing: border-box;
    //overflow-y: auto;

    .content {
      //width: 80%;
      //height: 1200px;
      background-color: #fff;
      border-radius: 10px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 10px;
      box-sizing: border-box;
      overflow-x: hidden;

      .item {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin: 20px 0;

        .qrcodeBox {
          width: 3rem;
          position: relative;


          .id {
            width: 15px;
            height: 15px;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            background-color: red;
            border-radius: 10px;
            color: #fff;
            position: absolute;
            top: -10px;
            left: 192px;
            font-size: .12rem;
          }
        }

        .right {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: center;

          .item_body {
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;
            margin: .05rem 0;

            .title {
              margin-right: 50px;
            }
          }
        }


        :deep(.el-card__body) {
          width: 100%;
          height: 100%;
          padding: 40px 20px;
          box-sizing: border-box;
          display: flex;
          justify-content: space-around;
          align-items: center;
        }


      }
    }

  }

}

// 滚动条样式
.scrollable-container {
  /* 当内容溢出时显示滚动条 */
  overflow-y: auto; /* 仅在垂直方向上滚动，如果需要水平滚动，可以使用overflow-x: auto 或 overflow: auto */
  /* 可选：为滚动条设置样式，注意这些样式在Webkit内核的浏览器（如Chrome、Safari）中生效 */
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: rgba(0, 0, 0, 0.2) rgba(255, 255, 255, 0.9); /* Firefox */

  /* 其他样式，如高度、宽度等，根据需要自行设置 */
  //height: 200px; /* 限制容器高度以演示滚动效果 */
  //border: 1px solid #ccc;
  padding: 10px;
}

//.slide-fade-enter-active {
//  transition: all 1s ease;
//}
.slide-fade-leave-active {
  //transition: all 1s cubic-bezier(1, 0.5, 0.8, 1);
  transition: all 0.5s ease-out

}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(30px);
  opacity: 0.5;
}

.move-up {
  transform: translateY(-50px); /* 100px (div2 height) + 10px (margin-bottom) */
}

</style>